# plugs/install.py
#
#

""" install plugins from remote site """

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import geturl2, rlog, waitforuser, hostnamere
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plugins import plugins
from gozerbot.config import config
from gozerbot.plughelp import plughelp
from gozerbot.aliases import aliases
import re, md5, urllib2

plughelp.add('install', 'install plugin from webserver')

def install(plugserver, dirr, what, ievent):
    """ install http://<plugserver>/<dir>/<plugin>.py from server """
    # fetch file signatures
    if not plugserver.startswith('http://'):
        plugserver = 'http://' + plugserver
    if what.endswith('.py'):
        what = what[:-3]
    try:
        sig = geturl2('%s/%s/signatures' % (plugserver, dirr))
    except urllib2.HTTPError:
        ievent.reply("can't find signatures file")
        return
    signatures = dict(re.findall('\((.*).py\) = (.*)', sig))
    # fetch plugin, check signature and save in plugs dir
    try:
        plug = geturl2('%s/%s/%s.py' % (plugserver, dirr, what))
    except urllib2.HTTPError:
        ievent.reply("no %s plugin on server" % what)
        return
    digest = md5.new(plug).hexdigest()
    try:
        digest2 = signatures[what]
    except KeyError:
        if ievent:
            ievent.reply("can't get md5 digest of %s" % what)
        else:
            rlog(10, 'install', "can't get md5 digest of %s" % what)
        return 0
    if not digest == digest2:
        if ievent:
            ievent.reply("md5 digest doesn't match .. not installing \
%s" % what)
        else:
            rlog(10, 'install', "md5 digest doesn't match .. not \
installing %s" % what)
        return 0
    plugfile = open('plugs/%s.py' % what,'w')
    plugfile.write(plug)
    plugfile.close()
    return 1

def handle_nonfree(bot, ievent):
    """ install a nonfree plugin .. aka a plugin with uses (c) code """
    # determine plugin name
    try:
        what = ievent.args[0]
    except IndexError:
        ievent.missing('<plugname>')
        return
    if what.endswith('.py'):
        what = what[:-3]
    ievent.reply('do take note that the file you are downloading is a \
derived work and has its own copyright (yes/no)')
    response =  waitforuser(bot, ievent.nick)
    if not response or response.txt != 'yes':
        ievent.reply('not installing %s' % what)
        return
    # get server to fetch plugin from
    plugserver = config['pluginserver']
    if not plugserver:
        plugserver = 'http://r8.cg.nu'
    ievent.reply('fetching %s' % what)
    if not install(plugserver, 'gozernonfree4', what, ievent):
        ievent.reply('error installing %s' % what)
        return
    plugins.reload('plugs', what)
    ievent.reply('%s reloaded' % what)

cmnds.add('install-nonfree', handle_nonfree, 'OPER')
examples.add('install-nonfree', 'install-nonfree <plugin> .. install plugin \
that has copyright(s)', 'install-nonfree dict')
aliases.data['nonfree'] = 'install-nonfree'

def handle_nonfreelist(bot, ievent):
    """ install-nonfreelist .. list the available nonfree plugs """
    plugserver = config['pluginserver']
    if not plugserver:
        plugserver = 'http://r8.cg.nu'
    pluglist = geturl2('%s/gozernonfree4/' % plugserver)
    result = re.findall('<A HREF="(.*?)\.py">', pluglist)
    ievent.reply(' .. '.join(result))

cmnds.add('install-nonfreelist', handle_nonfreelist, 'OPER')
examples.add('install-nonfreelist', 'list nonfree plugins that can be \
installed', 'install-nonfreelist')
aliases.data['nonfreelist'] = 'install-nonfreelist'

def handle_install(bot, ievent):
    """ install <server> <dir> <plugin> .. install plugin from server """
    try:
        (server, dirr, plug) = ievent.args
    except ValueError:
        ievent.missing("<server> <dir> <plug>")
        return
    if not re.match(hostnamere, server):
        ievent.reply('%s is not a valid hostname' % server)
        return
    if plug.endswith('.py'):
        plug = plug[:-3]
    ievent.reply('fetching %s' % plug)
    if not install(server, dirr, plug, ievent):
        ievent.reply('failed to install %s' % plug)
        return
    plugins.reload('plugs', plug)
    ievent.reply("%s reloaded" % plug)

cmnds.add('install', handle_install, 'OPER')
examples.add('install', 'install <server> <dir> <plug>: install \
http://<plugserver>/<dir>/<plugin>.py from server', 'install r8.cg.nu \
nonfree dict')
aliases.data['install-plug'] = 'install r8.cg.nu plugs'

def handle_installlist(bot, ievent):
    """ install-list .. list the available nonfree plugs """
    plugserver = config['pluginserver']
    if not plugserver:
        plugserver = 'http://r8.cg.nu'
    pluglist = geturl2('%s/plugs/' % plugserver)
    result = re.findall('<A HREF="(.*?)\.py">', pluglist)
    ievent.reply(' .. '.join(result))

cmnds.add('install-list', handle_installlist, 'OPER')
examples.add('install-list', 'list plugins that can be installed', \
'install-list')
